<?php 
$this->headLink(array('href' => '/cms/styles/style.css', 'rel' => "stylesheet", 'type' => "text/css"));
$this->headLink(array('href' => '/cms/styles/data-table.css', 'rel' => "stylesheet", 'type' => "text/css"));
$this->headLink(array('href' => '/cms/styles/popupMenu.css', 'rel' => "stylesheet", 'type' => "text/css"));

$this->headStyle(<<<EOD
#pathInterface {
	border: 1px dashed #CCCCCC;
	margin-top: 20px;
	margin-bottom: 20px;
	padding: 3px;
	min-height: 20px;
	background-color: #EBEBEB;
}
#pathBox {
	clear: both;
	float: none;
}
#pathBox ul {
	list-style-type:none;
	margin:0;
	padding:0;
}

#pathBox ul li {
	float:left;
	font-family:Arial,Helvetica,sans-serif;
	font-size:12px;
	margin:0;
	padding:0 10px 0 0;
}
#pathEditBox {
	clear: both;
	float: none;
}
.pupupMenu {
	display: none;
}
#pathBox .pupupMenu li {
	clear:both;
	float:none;
}
EOD
);

$this->headScript()
	->appendFile('/cms/scripts/dojo/dojo.js','',array('djConfig'=> 'parseOnLoad:true, isDebug:false'))
	->setAllowArbitraryAttributes(true);

$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/shadowbox/build/adapter/shadowbox-base.js');
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/shadowbox/build/shadowbox.js');

$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/content.js');
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/Popup.js');
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/SimpleMenu.js');
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/TableData.js');

$this->headScript(Zend_View_Helper_HeadScript::SCRIPT,"var catalogId = {$this->catalog_id};");

$this->headScript(Zend_View_Helper_HeadScript::SCRIPT,<<<EOD

//dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.InlineEditBox");
dojo.require("dojo.parser");
  
var shadowbox_callback = function () {};

reset_shadowbox_callback = function () {
	shadowbox_callback = function () {};
} 

Shadowbox.loadSkin('classic', '/cms/scripts/shadowbox/src/skin');
Shadowbox.loadLanguage('ru', '/cms/scripts/shadowbox/build/lang');
Shadowbox.loadPlayer(['html', 'iframe', 'img', 'swf'], '/cms/scripts/shadowbox/build/player');

window.onload = function () {
	Shadowbox.init(
    	{
			modal:		true,
			onClose: function() { shadowbox_callback() }
		}
	);
	
	goodsTable = new tableData('mainTable');
	
	goodsTable.registerWidget('cat_item_name',
		function (params) {
			var divEl = document.createElement('div');
			divEl.setAttribute('dojoType','dijit.InlineEditBox');
			divEl.innerHTML = params['value']=='' ? 'Нет заголовка' : params['value'];
			
			new dijit.InlineEditBox({
					autoSave:true,
					renderAsHtml:true,
					onChange: function (value) {
							dojo.xhrGet({
							    url: "/cms/catalog/change/cat_id/"+catalogId+"/id/"+params['id']+"/title/"+value,
							    load: function(response, ioArgs){
							      return response;
							    },
							    error: function(response, ioArgs){
							      alert(response);
							      return response;
							    },
							    handleAs: "text"
							  });
					
						}
				}, divEl);
			
			
								
			
			return divEl;
		});
		
	goodsTable.registerWidget('price',
		function (params) {
			var divEl = document.createElement('div');
			divEl.style.textAlign = 'right';
			divEl.setAttribute('dojoType','dijit.InlineEditBox');
			divEl.innerHTML = params['value']=='' ? 'Нет заголовка' : params['value'];
			
			new dijit.InlineEditBox({
					autoSave:true,
					renderAsHtml:true,
					onChange: function (value) {
							dojo.xhrGet({
							    url: "/cms/catalog/change/cat_id/"+catalogId+"/id/"+params['id']+"/price/"+value,
							    load: function(response, ioArgs){
							      return response;
							    },
							    error: function(response, ioArgs){
							      alert(response);
							      return response;
							    },
							    handleAs: "text"
							  });
					
						}
				}, divEl);
			
			
								
			
			return divEl;
		});
		
		
	goodsTable.registerWidget('new_f',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.className = 'icon';
			
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/' + (params['value']=='0' ? 'star_empty.png' : 'star.png');
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					dojo.xhrGet({
						url: "/cms/catalog/change/cat_id/"+catalogId+"/id/"+params['id']+"/new_f/1",
						load: function(response, ioArgs) {
						  imgEl.src = '/cms/images/' + (parseInt(response) == 1 ? 'star.png' : 'star_empty.png'); 
						  return response;
						},
						error: function(response, ioArgs){
						  alert("An error occurred, with response: " + response);
						  return response;
						},
						handleAs: "text",
						sync: true
					  });
				}
			
			
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);
			
			return divEl;
		});
		
	goodsTable.registerWidget('sales_leader_f',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.className = 'icon';
			
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/' + (params['value']=='0' ? 'crown_silver.png' : 'crown.png');
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					dojo.xhrGet({
						url: "/cms/catalog/change/cat_id/"+catalogId+"/id/"+params['id']+"/sales_leader_f/1",
						load: function(response, ioArgs) {
						  imgEl.src = '/cms/images/' + (parseInt(response) == 1 ? 'crown.png' : 'crown_silver.png'); 
						  return response;
						},
						error: function(response, ioArgs){
						  alert("An error occurred, with response: " + response);
						  return response;
						},
						handleAs: "text",
						sync: true
					  });
				}
			
			
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);
			
			return divEl;
		});
		
	goodsTable.registerWidget('cat_item_categories',
		function (params) {
			var divEl = document.createElement('DIV');
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					shadowbox_callback = function () {
						dojo.xhrGet({
							url: "/cms/catalog/categorylist/cat_id/"+catalogId+"/id/"+params['id']+"/",
							load: function(response, ioArgs) {
							  aEl.innerHTML = '';
							  if (parseInt(response)==0) {
							    divEl.className = 'icon';
							    var im = document.createElement('IMG');
							    im.src = '/cms/images/tags_plus.png';
							    aEl.appendChild(im);
							  } else {
								divEl.className = 'long-data';
							    aEl.innerHTML = response;
							  }
							  
							
							  //imgEl.src = '/cms/images/' + (parseInt(response) == 1 ? 'document_text.png' : 'document_plus.png'); 
							  return response;
							},
							error: function(response, ioArgs){
							  alert("An error occurred, with response: " + response);
							  return response;
							},
							handleAs: "text",
							sync: true
						  });
						shadowbox_callback = function () {};
					}
					
					Shadowbox.open({
					    player:     'iframe',
					    title:      'Изменение привязки к категориям',
					    content:    '/cms/catalog/categorylink/cat_id/'+catalogId+'/id/'+params['id'],
					    height:     450,
					    width:      750
					});
				}
			
			
			if (params['value']=='') {
				divEl.className = 'icon';
				var imgEl = document.createElement('IMG');
				imgEl.src = '/cms/images/tags_plus.png';
				aEl.appendChild(imgEl);
			} else {
				divEl.className = 'long-data';
				aEl.innerHTML = params['value'];
			}
			
			divEl.appendChild(aEl);
							
			return divEl;
		});
		
		
		
	goodsTable.registerWidget('standart_parameters',
		function (params) {
			var divEl = document.createElement('DIV');
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					
					Shadowbox.open({
					    player:     'iframe',
					    title:      'Изменение стандартный параметров',
					    content:    "/cms/catalog/catalogparametrs/cat_id/"+catalogId+"/id/"+params['id']+"/",
					    height:     450,
					    width:      750
					});
				}
			
			
			divEl.className = 'icon';
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/document_list.png';
			aEl.appendChild(imgEl);
			
			divEl.appendChild(aEl);
							
			return divEl;
		});	
		
		
		
	goodsTable.registerWidget('parameters',
		function (params) {
			var divEl = document.createElement('DIV');
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					
					Shadowbox.open({
					    player:     'iframe',
					    title:      'Изменение опциональных параметров',
					    content:    "/cms/catalog/optionalparametrs/cat_id/"+catalogId+"/id/"+params['id']+"/",
					    height:     450,
					    width:      750
					});
				}
			
			
			divEl.className = 'icon';
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/document_list.png';
			aEl.appendChild(imgEl);
			
			divEl.appendChild(aEl);
							
			return divEl;
		});	
		
	goodsTable.registerWidget('cat_item_delete',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.className = 'icon';
			
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/cross.png';
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					
					if (!confirm('Удалить позицию каталога?')) {
						return false;
					}
					
					var delete_params = new Array();
					for (var f=0;f<filter_setup.length;f++) {
						delete_params.push(filter_setup[f]);
					}
					delete_params.push('act','del','item_id',params['id']);
					callData(delete_params);
					
				}
			
			
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);
			
			return divEl;
		});
		
	
	
	
	categoryList = new tableData('categTable');
	
	categoryList.registerWidget('category_name',
		function (params) {
			var divEl = document.createElement('div');
			divEl.setAttribute('dojoType','dijit.InlineEditBox');
			divEl.innerHTML = params['value']=='' ? 'Нет заголовка' : params['value'];
			
			new dijit.InlineEditBox({
					autoSave:true,
					renderAsHtml:true,
					onChange: function (value) {
							dojo.xhrGet({
							    url: "/cms/catalog/changecateg/cat_id/"+catalogId+"/id/"+params['id']+"/title/"+value,
							    load: function(response, ioArgs){
							      loadPath();
							      return response;
							    },
							    error: function(response, ioArgs){
							      alert(response);
							      return response;
							    },
							    handleAs: "text"
							  });
						}
				}, divEl);
			
			
								
			
			return divEl;
		});
	
	categoryList.registerWidget('category_delete',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.className = 'icon';
			
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/cross.png';
			
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
					
					if (!confirm('Удалить категорию из каталога?')) {
						return false;
					}
					
					loadCateg(['act','del','item_id',params['id']]);
					
				}
			
			
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);
			
			return divEl;
		});
		
	//callData([]);
	gotoCateg(0);
}

var addItem = function() {
	current_page = 1;
	limit_setup = [0,rows_per_page];
	callData(['act','add']);
}

var callData = function (params) {
	
	dojo.xhrGet({
	    url: "/cms/catalog/data/id/"+catalogId+"/limit_from/"+limit_setup[0]+"/limit_amount/"+limit_setup[1]+'/cat_id/'+cat_id+'/'+params.join('/'),
	    load: function(responseObject, ioArgs){
	      var pagesPlace = document.getElementById('pagesPlace');
	      pagesPlace.innerHTML = '';
	      
	      var total_pages = Math.ceil(responseObject['total_length']/rows_per_page);
	      
	      var appendPageAction = function (page) {
	        var aEl = document.createElement('A');
	      	aEl.innerHTML = i;
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(page) }
	      	return aEl;
	      }
	      
	      var appendDelimetr = function () {
	        var delimetr = document.createElement('SPAN');
	      	delimetr.innerHTML = '&nbsp;';
	      	return delimetr;
	      }
	      
	      
	      if (current_page>1) {
	      	var aEl = document.createElement('A');
	      	aEl.innerHTML = '&lt; Предыдущая';
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(current_page-1) }
	      	pagesPlace.appendChild(aEl);
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
	      var start_from = current_page-3;
	      if (start_from>1) {
	      	var dots = document.createElement('SPAN');
	      	dots.innerHTML = '...&nbsp;';
	      	pagesPlace.appendChild(dots);
	      } else {
	      	start_from = 1;
	      }
	      for (var i=start_from;i<current_page;i++) {
	      	pagesPlace.appendChild(appendPageAction(i));
	      	
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
	      var cur_pg = document.createElement('SPAN');
	      cur_pg.innerHTML = current_page;
	      pagesPlace.appendChild(cur_pg)
	      
	      pagesPlace.appendChild(appendDelimetr());
	      	
	      	
	      var end_to = current_page+3;
	      if (end_to>total_pages) end_to = total_pages;
	      
	      for (var i=current_page+1;i<=end_to;i++) {
	      	pagesPlace.appendChild(appendPageAction(i));
	      	
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
	      if (end_to<total_pages) {
	        var dots = document.createElement('SPAN');
	      	dots.innerHTML = '...&nbsp;';
	      	pagesPlace.appendChild(dots);
	      }
	      
	      if (current_page<total_pages) {
	      	var aEl = document.createElement('A');
	      	aEl.innerHTML = 'Следующая &gt;';
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(current_page+1) }
	      	pagesPlace.appendChild(aEl);
	      	pagesPlace.appendChild(appendDelimetr());
	      }
	      
		  goodsTable.draw(responseObject['data']);
		  
		  
		  //dojo.parser.parse(document.getElementById('mainNewsTable'));
		  
	      return responseObject;
	    },
	    error: function(response, ioArgs){
	      alert("An error occurred, with response: " + response);
	      return response;
	    },
	    handleAs: "json",
	    sync: true
	  });
}

var current_page = 1;
var rows_per_page = 10;
var limit_setup = [0,rows_per_page];
var cat_id = 0;

var gotoPage = function (page) {
	current_page = page;
	limit_setup = [(page-1)*rows_per_page,rows_per_page];
	callData(filter_setup);
}

var filter_setup = new Array();
var MakeFilter = function () {
	filter_setup = ['from_date',document.getElementById('from_date').value,'to_date',document.getElementById('to_date').value];
	if (document.getElementById('publish_f').checked) {
		filter_setup.push('publish_f','1');
	}
	
	gotoPage(1);
}


var foldEditBox = function  () {
	var foldStyle = dojo.byId('pathEditBox').style;	
	foldStyle.display = foldStyle.display=='none' ? '' : 'none';
}



var appendPopupPathAction = function (event,trigger,target) {
	// данный скрипт производит мутацию событий на объекте. вызывает обект popupArea 
	// который навешивает собственные события и удаляет старые. 
	// в конце на обекте происходит вызов события

	if (typeof target == 'string') {
		target = document.getElementById(target);
	} 
	var ulElement = target.getElementsByTagName('UL');
	new SimpleMenu(ulElement[0]);
	
	var SplashPathMenuAdaptor = function (popupMenuObj) {
		popupMenuObj.triggerEl.onmouseover = function (e) {
				if (navigator.appName=='Netscape') {
					var popupLeft = e.clientX;
					var popupTop = e.clientY+popupMenuObj.triggerEl.height;
				} else {
					var popupLeft = event.clientX-event.offsetX;
					var popupTop = event.clientY+(popupMenuObj.triggerEl.height-event.offsetX);
				}
				popupMenuObj.areaEl.style.left = popupLeft+'px';
				popupMenuObj.areaEl.style.top  = popupTop+'px';
				popupMenuObj.show(popupMenuObj);
			};
			
		popupMenuObj.triggerEl.onmouseout = function () { popupMenuObj.hide(popupMenuObj) };
		popupMenuObj.areaEl.onmouseover = function () { popupMenuObj.show(popupMenuObj) };
		popupMenuObj.areaEl.onmouseout = function () { popupMenuObj.hide(popupMenuObj) };
		
	}
	
	new PopupArea(trigger,target,SplashPathMenuAdaptor);
	
	
	if (navigator.appName=="MSIE" || navigator.appName.indexOf('Microsoft')!='-1') {
		trigger.fireEvent('onmouseover');
	} else {
		var ent = document.createEvent('MouseEvents');
		ent.initMouseEvent('mouseover', true, true, window, 1, event.screenX, event.screenY, event.clientX, event.clientY, false, false, false, false, 0, null);
		trigger.dispatchEvent(ent);
	}
}

var gotoCateg = function (id) {
	cat_id = id;
	callData([]);
	loadCateg([]);
}
	
var loadCateg = function (params) {

	dojo.xhrGet({
	    url: "/cms/catalog/datacateg/cat_id/"+catalogId+'/id/'+cat_id+'/'+params.join('/'),
	    load: function(responseObject, ioArgs){
		  categoryList.draw(responseObject);
	      return responseObject;
	    },
	    error: function(response, ioArgs){
	      alert("An error occurred, with response: " + response);
	      return response;
	    },
	    handleAs: "json",
	    sync: true
	  });
	
	loadPath();
}

var loadPath = function () {
	dojo.xhrGet({
	    url: "/cms/catalog/path/cat_id/"+catalogId+"/id/"+cat_id,
	    load: function(response, ioArgs){
	      dojo.byId("pathBox").innerHTML = response;
	      return response;
	    },
	    error: function(response, ioArgs){
	      dojo.byId("pathBox").innerHTML = 
	        "An error occurred, with response: " + response;
	      return response;
	    },
	    handleAs: "text"
	  });
}
EOD
);




$this->layout()->body_attr = 'class="modal"';
?>
<div id="pathInterface">
  <div id="pathBox"></div>
  <div id="pathEditBox" style="display: none">
  <div<?= $this->edit_categ=='1' ? '' : ' style="display: none"' ?>>
    <div style="margin-bottom:10px; margin-top:30px"><button class="okButton" onclick="loadCateg(['act','add'])"><img src="/cms/images/plus.png" width="16" height="16" align="absmiddle" /> Добавить категорию</button></div>
    <table width="100%" cellspacing="0" class="table-data">
	<thead>
	  <tr>
	    <th nowrap="nowrap" scope="col">Название</th>
<?php for ($d=0;$d<count($this->category_data_map);$d++) {?>
	    <th width="100" nowrap="nowrap" scope="col"><?= $this->category_data_map[$d] ?></th>
<?php } ?>
	    <th width="34" nowrap="nowrap" scope="col">&nbsp;</th>
	  </tr>
	</thead>
	<tbody id="categTable"></tbody>
	</table>
  </div>
  </div>
</div>
  
<p class="stnd_font">
  <button class="okButton" onclick="addItem()"><img src="/cms/images/plus.png" width="16" height="16" align="absmiddle" /> Добавить новую позицию</button></p>
<p class="stnd_font">Страницы: <span id="pagesPlace">&nbsp;</span></p>
<table width="100%" cellspacing="0" class="table-data">
<thead>
  <tr>
    <th nowrap="nowrap" scope="col">Название</th>
    <th nowrap="nowrap" scope="col">Категория</th>
<?php for ($d=0;$d<count($this->data_map);$d++) {?>
    <th width="100" nowrap="nowrap" scope="col"><?= $this->data_map[$d] ?></th>
<?php } ?>
    <th width="34" nowrap="nowrap" scope="col">&nbsp;</th>
  </tr>
</thead>
<tbody id="mainTable"></tbody>
</table>